import javax.jws.WebService;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 仓库管理类的WebService的实现类
 *
 * @author Chova
 * @date 2022/05/30
 */
@WebService(targetNamespace = "WsInventory")
public class WsInventoryImpl implements WsInventory {

    static List<Inventory> inventoryList = new ArrayList<>();

    @Override
    public void save(String inventoryStr) {
        saveInventory(inventoryStr);
    }

    /**
     * 将输入的字符串转换为实体类
     *
     * @param entityStr 实体类字符串
     * @return Inventory 实体类
     */
    static Inventory strToEntity(String entityStr) {
        Inventory inventory = new Inventory();

        String[] entityArray = entityStr.split(" ");
        inventory.setInventoryName(entityArray[0]);
        inventory.setInventoryNo(entityArray[1]);
        inventory.setMaterialName(entityArray[2]);
        inventory.setMaterialNo(entityArray[3]);
        inventory.setCount(Integer.parseInt(entityArray[4]));

        return inventory;
    }

    /**
     * 新增一条仓库记录
     *
     * @param inventoryStr 仓库记录
     * @return List<Inventory> 仓库记录列表
     */
    static List<Inventory> saveInventory(String inventoryStr) {
        Inventory inventory = strToEntity(inventoryStr);
        Inventory inventoryFind = null;
        int indexFind = 0;
        // 查找相同仓库号、物料号的数量的记录
        for (int i = 0; i < inventoryList.size(); i++) {
            Inventory inventoryOld = inventoryList.get(i);
            if (null != inventoryOld && Objects.equals(inventory.getInventoryNo(), inventoryOld.getInventoryNo()) && Objects.equals(inventory.getCount(), inventoryOld.getCount())) {
                inventoryFind = inventoryOld;
                indexFind = i;
                break;
            }
            continue;
        }
        // 相同仓库号、物料号的数量的记录执行更新.否则新增一条记录
        if (null != inventoryFind) {
            inventoryList.set(indexFind, inventory);
        } else {
            inventoryList.add(inventory);
        }

        return inventoryList;
    }
}
